<?php
/**
 *
 * @deprecated 下线功能
 * Description: 自定义导入Excel-push 推送
 * Created by PhpStorm.
 * User: 玉坤
 * Date: 2021/6/7
 * Time: 16:06
 */
class test{

}

use Biz\cache\wiki\Union;
use Biz\model\push\PushLogModel;
use Doraemon\tools\LinkFormat;

ini_set('display_errors', 1);
error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING ^ E_DEPRECATED);
ini_set('memory_limit', '1024M');

require_once '/data/wwwroot/g_vendor/autoload.php';
main();

/*
for ($i = 0; $i < 60; $i++) {
    //每分钟执行1次，执行60分钟，60次
    var_dump('执行第' . ($i + 1) . '次');
    main();
    sleep(60);
}
*/

function main()
{
    $start = microtime(true);
    $page = 1;
    $pageSize = 10;
    $list = [];
    $all_num = 0;


    try {
        do {
            $limit = [($page - 1) * $pageSize, $pageSize];
            //定时执行时间
            $where = [
                'start_time' => date("Y-m-d H:i:00"),
                "LIMIT" => $limit,
                'push_status' => PushLogModel::STATUS_WAIT
            ];
            $list = PushLogModel::all($where, '*');
            \Doraemon\tools\Log::debug('自定义push-info:', $list);
            if ($list) {
                foreach ($list as $item) {

                    $file_path = $item['file_name'] ?? '';
                    if (!$file_path) {
                        continue;
                    }
                    $isset = file_exists($file_path);
                    if (!$isset) {
                        continue;
                    }
                    $link = $item['url'] ?? '';
//                if (!$link) {
//                    continue;
//                }


                    $push_id = $item['push_id'] ?? 0;
                    if (!$push_id || !$item['title'] || !$item['alert']) {
                        continue;
                    }

                    $data['link'] = $link;
                    $data['push_id'] = $push_id;
                    $data['push_type'] = $item['push_type'];
                    if ((int)$data['push_type'] === PushLogModel::PUSH_TYPE_SPECIAL) {
                        $data['title'] = json_decode($item['title'], true) ?: [];
                        $data['alert'] = json_decode($item['alert'], true) ?: [];
                        if (!$data['title'] || !$data['alert']) {
                            continue;
                        }
                    } else {
                        $data['title'] = $item['title'];
                        $data['alert'] = $item['alert'];
                    }

                    $msg = getMsg($data);
                    addPush($file_path, $msg, $item['id']);
                }
            }
            $page++;
        } while ($list);
    } catch (\Exception $e) {
        \Doraemon\tools\Log::error('自定义push-error:' . $e->getMessage(), $list);
    }
    $end = microtime(true);
    $time = $end - $start;
    $second = round($time, 3);
    var_dump('完成时间：' . date('Y-m-d H:i:s') . '共' . $all_num . '条数据，发送完成' . '   总耗时:' . $second . '秒');
}

function getMsg($data)
{
    //自定义推送
    if ((int)$data['push_type'] === PushLogModel::PUSH_TYPE_SPECIAL) {
        $title = $data['title']['values'];
        $alert = $data['alert']['values'];
    } else {
        $title = $data['title'];
        $alert = $data['alert'];
    }
    return [
        'push_type' => $data['push_type'],
        'title' => $title,
        'alert' => $alert,
        'param' => [
            'link' => $data['link'] ?? '',
            'push_id' => $data['push_id'],
            'image' => ''
        ]
    ];
}


function addPush($fileName, $msg, $id)
{
    //修改为推送中
    PushLogModel::update(['push_status' => PushLogModel::STATUS_SENDING], ['id' => $id]);

    $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($fileName);
    $sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
    $all_num = count($sheetData) - 1;
    $send_data = [];
//    $key = $msg['param']['push_id'];
    $new_msg = [];
    if ($sheetData && is_array($sheetData)) {
        foreach ($sheetData as $i => $goods_item) {
            if ($i < 2) {
                continue;
            }
            if (!$goods_item) {
                continue;
            }
            $new_msg['title'] = is_array($msg['title']) ? formatData($msg['title'], $goods_item) : $msg['title'];
            $new_msg['alert'] = is_array($msg['alert']) ? formatData($msg['alert'], $goods_item) : $msg['alert'];
            $new_msg['param'] = $msg['param'];

            if (isset($goods_item['A']) && $goods_item['A']) {
                $new_msg['uid'] = $goods_item['A'];
                $res = \Doraemon\service\Push\PushService::send($new_msg);
                if ($res) {
                    $send_data[] = $new_msg['uid'];
                }
            }
        }
        var_dump($send_data);
        $up_data['all_num'] = $all_num ?? 0;
        $up_data['send_num'] = count($send_data);
        $up_data['update_time'] = date("Y-m-d H:i:s");
        $up_data['end_time'] = date("Y-m-d H:i:s");
        if ($send_data) {
            $up_data['push_status'] = PushLogModel::STATUS_OVER;
            unlink($fileName);
        } else {
            $up_data['push_status'] = PushLogModel::STATUS_FAIL;
        }
//        \Biz\cache\PushRedis\PushRedis::setItem($key, $send_data, 60 * 60 * 24);
        //更改状态为已推送
        PushLogModel::update($up_data, ['id' => $id]);
    }


}


function formatData($title_data, $goods_item)
{
    $arr = [
        'B',
        'C',
        'D',
        'E',
        'F',
        'G',
        'H',
        'I',
        'J',
        'K',
        'L',
        'M',
        'N',
        'O',
        'P',
        'Q',
        'R',
        'S',
        'T',
        'U',
        'V',
        'W',
        'X',
        'Y',
        'Z'
    ];
    $str = '';
    foreach ($title_data as $v) {
        if (in_array($v, $arr, true)) {
            $v = isset($goods_item[$v]) && $goods_item[$v] ? trim($goods_item[$v]) : '';
        }
        $str .= $v;
    }
    return $str;
}
